from src.dicom_viewer_be_mock_xiaosai.utils.logger import logger

class DicomLoader:
    series_dict = {}
    series_filename_dict = {}
    sop_instance_set = set()

    @staticmethod
    def save_filename_dict(each_record):
        series_id = each_record['series_id']
        filename = each_record['filename']
        if series_id in DicomLoader.series_filename_dict:
            DicomLoader.series_filename_dict[series_id].append(filename)
        else:
            DicomLoader.series_filename_dict[series_id] = [filename]


    @staticmethod
    async def classify_ds_arr(ds_arr):
        for ds in ds_arr:
            DicomLoader.classify_a_dicom(ds)
        DicomLoader.turn_series_dict_to_order()


    @staticmethod
    def classify_a_dicom(ds):
        if hasattr(ds, 'SeriesInstanceUID') is False:
            raise ValueError("SeriesUID not exist")
        series_uid = ds.SeriesInstanceUID
        sop_instance_uid = ds.SOPInstanceUID if hasattr(ds, 'SOPInstanceUID') else None
        if sop_instance_uid in DicomLoader.sop_instance_set:
            logger.info('重复的sop instance')
            return
        else:
            DicomLoader.sop_instance_set.add(sop_instance_uid)
            sop_arr = DicomLoader.series_dict.get(series_uid, [])
            sop_arr.append(ds)
            DicomLoader.series_dict[series_uid] =sop_arr




    @staticmethod
    def turn_series_dict_to_order():
        for series_id in DicomLoader.series_dict:
            dicoms = DicomLoader.series_dict[series_id]
            dicoms.sort(key=lambda x: int(x.InstanceNumber))
            DicomLoader.series_dict[series_id] = dicoms
